package cn.shanks.springbootshirojwt.config.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

/**
 * @author Shanks
 * @version 1.0
 * @program cn.shanks.springbootshirojwt.config.shiro
 * @description
 * @date 2020/11/10 11:07
 */
public class ShiroRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 获取授权信息
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // principals.toString()之后即为token
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 设置用户
        Set<String> roles = new HashSet<>();
        roles.add("管理员");
        simpleAuthorizationInfo.setRoles(roles);
        // 设置权限
        Set<String> pers = new HashSet<>();
        pers.add("test:get");
        simpleAuthorizationInfo.setStringPermissions(pers);
        return simpleAuthorizationInfo;
    }

    /**
     * 获取登录信息
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 这里编写token验证规则，若失败，抛出异常
        System.out.println("验证token是否有效");
        return new SimpleAuthenticationInfo(token.getCredentials(), token.getCredentials(), "jwttoken");
    }
}
